/**
 * 用户信息的dao
 * 离线模式的时候使用
 * @flow
 */

import AsyncStorage from '@react-native-community/async-storage';
import JsonUtils from '../utils/JsonUtils';

export const STORE_KEY = 'USER_INFO';
export const TOKEN_KEY = 'X-FM-SHOOTING-TOKEN';

export default class UserDao {
  /**
   * 保存用户信息 用户名 头像 id
   * @param value 用户信息 {userName, headImageUrl, userID}
   * @param callback
   */
  static saveUserInfo(value, callback) {
    AsyncStorage.setItem(STORE_KEY, JsonUtils.jsonToStr(value), callback);
  }

  // 保存用户token
  static saveUserToken(value) {
    AsyncStorage.setItem(TOKEN_KEY, value);
  }

  static clearUserToken() {
    return new Promise((resolve, reject) => {
      AsyncStorage.setItem(TOKEN_KEY, '', error => {
        if (!error) {
          resolve()
        } else {
          reject(error)
        }
      });
    })
  }

  /**
   * 获取用户信息
   * @returns {Promise<any>}
   */
  static getUserInfo() {
    return new Promise((resolve, reject) => {
      AsyncStorage.getItem(STORE_KEY, (error, result) => {
        if (!error) {
          try {
            resolve(JsonUtils.strToJson(result));
          } catch (e) {
            reject(error);
          }
        } else {
          reject(error);
        }
      });
    });
  }

  // 获取用户token
  static getUserToken() {
    return new Promise((resolve, reject) => {
      AsyncStorage.getItem(TOKEN_KEY, (error, result) => {
        if (!error) {
          try {
            resolve(result);
          } catch (e) {
            reject(error);
          }
        } else {
          reject(error);
        }
      });
    });
  }
}

